package com.starry.module.system.core.checkcode.service.impl;

import com.starry.core.common.execption.ServiceException;
import com.starry.core.redis.service.RedisService;
import com.starry.module.system.api.checkcode.domain.qo.CaptchaCreateQo;
import com.starry.module.system.api.checkcode.domain.vo.CaptchaVo;
import com.starry.module.system.core.checkcode.service.CaptchaStrategy;
import com.starry.module.system.core.sms.service.SmsService;
import org.springframework.stereotype.Service;

import static com.starry.module.system.core.redis.RedisKeyConstants.AUTH_CHECK_CODE;

/**
 * @Description 发送验证码
 * @Author xiaoke
 */
@Service("sms_captcha")
public class SmsCaptchaStrategy implements CaptchaStrategy {


    private final RedisService redisService;
    private final SmsService smsService;

    public SmsCaptchaStrategy(RedisService redisService, SmsService smsService) {
        this.redisService = redisService;
        this.smsService = smsService;
    }

    @Override
    public CaptchaVo generateCaptcha(CaptchaCreateQo qo) {
        String cellphone = qo.getCellphone();
        if (cellphone == null || cellphone.isEmpty()) {
            throw new ServiceException("手机号码不能为空");
        }

        // 删除上次发送的验证码
        String key = AUTH_CHECK_CODE + qo.getCodeType() + ":" + cellphone;
        if (redisService.hasKey(key)) {
            redisService.deleteObject(key);
        }

        String send = smsService.send(cellphone);
        if (send == null) {
            throw new ServiceException("验证码发送失败，请稍后重试");
        }
        return CaptchaVo.builder()
                .result(send)
                .key(cellphone)
                .build();
    }
}
